﻿using ASmile.Com;
using ASmile.Com.Report;
using ASmile.DBModel;
using ASmile.Extend;
using ASmile.Win.Controls;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace ASmile.Win.Forms
{
    public partial class FrmViewReport : FrmBase
    {
        public FrmViewReport()
        {
            InitializeComponent();
        }

        public override string ContainerName
        {
            get
            {
                if (MenuArgs.IsEmpty())
                {
                    return base.ContainerName;
                }
                return MenuArgs;
            }
            protected set { }
        }

        IReportBLL BLLObj { get; } = ObjectFactory.GetObject<IReportBLL>("ReportBLL");

        Sys_Report ReportMain { set; get; }

        List<Sys_ReportArg> ReportArgs { set; get; }

        ArgGetReport ArgVModel { get; } = new ArgGetReport();

        /// <summary>
        /// 创建参数控件
        /// </summary>
        void InitArgControl()
        {
            QueryArg.FormName = ContainerName;
            QueryArg.ArgList = new Dictionary<string, string>();
            ucPageNav.Visible = ReportMain.IsPager;
            statusStrip.Visible = !ReportMain.IsPager;
            if (ucPageNav.Visible)
            {
                ucPageNav.PageChangedEvent += GetPageData;
            }
            tsTxtSearch.Visible = ReportMain.IsSearchTxt;
            tsBtnPrint.Visible = ReportMain.IsPrint;
            tsBtnOut.Visible = ReportMain.IsOut;
            if (ReportArgs == null || ReportArgs.Count == 0) return;

            var data = ReportArgs.OrderByDescending(s => s.OrderNo);

            foreach (var item in data)
            {
                ToolStrip ts;
                if (item.ToolStripNo == 0)
                {
                    ts = toolStrip1;
                }
                else if (item.ToolStripNo == 1)
                {
                    ts = toolStrip2;
                    toolStrip2.Visible = true;
                }
                else if (item.ToolStripNo == 2)
                {
                    ts = toolStrip3;
                    toolStrip2.Visible = true;
                }
                else
                {
                    MessageBox.Show("工具栏编号配置错误");
                    return;
                }
                ToolStripItem tsItem;
                var cType = (EmControlType)item.ControlType;
                switch (cType)
                {
                    case EmControlType.日期时间:
                        tsItem = CreateDatePicker(item);
                        break;
                    case EmControlType.下拉列表:
                        tsItem = CreateComboBox(item);
                        break;
                    case EmControlType.文本框:
                        tsItem = CreateTextBox(item);
                        break;
                    case EmControlType.时间:
                        tsItem = CreateTimeSpan(item);
                        break;
                    default:
                        MessageBox.Show("控件类型配置错误");
                        return;
                }
                tsItem.Tag = item;

                if (item.IsSplit)
                {
                    ts.Items.Insert(0, new ToolStripSeparator());
                }
                ts.Items.Insert(0, tsItem);
                ts.Items.Insert(0, new ToolStripLabel() { Text = item.Caption });
                if (tsItem is ToolStripComboBox coBox)
                {
                    if (int.TryParse(item.DefaultValue, out int defVal))
                    {
                        if (defVal < coBox.Items.Count) coBox.SelectedIndex = defVal;
                    }
                    else
                    {
                        tsItem.Text = item.DefaultValue;
                    }
                }
            }
        }

        void InitKeyDown()
        {
            if (!IsManager) return;
            this.KeyPreview = true;
            KeyDown += FrmViewReport_KeyDown;
        }

        void RefreshPrintData()
        {
            foreach (Control item in panelMain.Controls)
            {
                item.Dispose();
            }
            panelMain.Controls.Clear();
            var arg = new PrintReportArg();

            SetQueryArg();
            var ret = BLLObj.GetPrintData(QueryArg);
            if (!ret)
            {
                ShowMessage(ret.msg);
                return;
            }

            

            arg.DetailData = ret.data.DetailData.ToDataTable();
            arg.ParameterData = new object[] { ret.data.Args };
            var frm = PrintHelper.GetPrintForm(this, arg);
            frm.FormBorderStyle = FormBorderStyle.None;
            frm.Dock = DockStyle.Fill;
            frm.TopLevel = false;
            panelMain.Controls.Add(frm);
            frm.Show();
        }

        private void FrmViewReport_Load(object sender, EventArgs e)
        {
            InitKeyDown();
            ArgVModel.FormName = ContainerName;

             var ret = BLLObj.GetVModel(ArgVModel);
            if (ret == null)
            {
                MessageBox.Show("未配置报表，需管理员 Ctrl + 3 进行配置 ");
                return;
            }
            ReportMain = ret.data.ReportMain;
            ReportArgs = ret.data.ReportArgs;
            if (ReportMain == null)
            {
                MessageBox.Show("未配置报表主目，需管理员 Ctrl + 3 进行配置 ");
            }
            InitArgControl();

            if (ReportMain.ReportType == ((int)EmReportType.打印预览))
            {
                RefreshPrintData();
            }
            dgv.SetDoubleBuffered(true);
        }

        private void tsbtnExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void FrmViewReport_KeyDown(object sender, KeyEventArgs e)
        {
            if (!IsManager) return;

            if (Control.ModifierKeys == Keys.Control && e.KeyCode == Keys.D3)
            {
                FrmCfgReport frm = new FrmCfgReport();
                frm.Owner = this;
                frm.StartPosition = FormStartPosition.CenterParent;
                frm.ShowDialog();
                return;
            }
        }

        ToolStripItem CreateDatePicker(Sys_ReportArg arg)
        {
            var tsItem = new ToolStripDateTimePicker()
            {
                CustomFormat = arg.DataFormat,
                Format = DateTimePickerFormat.Custom,
            };
            if (arg.DefaultValue.IsEmpty())
            {
                tsItem.Value = DateTime.Now;
                return tsItem;
            }
            var defArgs = arg.DefaultValue.SplitByNotEmpty(",");
            var defVal = defArgs[0].ToInt();
            if (defVal == 0)
            {
                tsItem.Value = DateTime.Now;
                return tsItem;
            }
            if (defArgs.Length > 1)
            {
                var defType = defArgs[1];
                if (defType.StringEquals("y"))
                {
                    tsItem.Value = DateTime.Now.AddYears(defVal);
                }
                else if (defType.StringEquals("m"))
                {
                    tsItem.Value = DateTime.Now.AddMonths(defVal);
                }
                else
                {
                    tsItem.Value = DateTime.Now.AddDays(defVal);
                }
                return tsItem;
            }
            else
            {
                tsItem.Value = DateTime.Now.AddDays(defVal);
                return tsItem;
            }
        }

        ToolStripItem CreateTimeSpan(Sys_ReportArg arg)
        {
            var tsItem = new TollStripTimeSpan();
            var defVal = arg.DefaultValue.ToDouble();
            tsItem.Value = TimeSpan.FromMinutes(defVal);
            return tsItem;
        }

        class ComBoxDataSource
        {
            public string Id { set; get; }

            public string Val { set; get; }
        }

        ToolStripItem CreateComboBox(Sys_ReportArg arg)
        {
            var tsItem = new ToolStripComboBox();
            tsItem.DropDownStyle = ComboBoxStyle.DropDownList;
            if (arg.DataSource.IsEmpty() || arg.DataSourceList == null)
            {
                MessageBox.Show($"参数：{arg.ArgName} 未绑定数据源");
                return tsItem;
            }
            tsItem.ComboBox.ValueMember = "Id";
            tsItem.ComboBox.DisplayMember = "Val";

            foreach (var item in arg.DataSourceList)
            {
                tsItem.Items.Add(item);
            }

            tsItem.ComboBox.DataSource = arg.DataSourceList;

            return tsItem;
        }

        ToolStripItem CreateTextBox(Sys_ReportArg arg)
        {
            var tsItem = new ToolStripTextBox();
            if (arg.ControlWidth > 0)
            {
                tsItem.Size = new Size(arg.ControlWidth, 0);
            }
            return tsItem;
        }

        ArgReportData QueryArg { get; } = new ArgReportData();

        void RefreshData()
        {
            if (ucPageNav.Visible)
            {
                GetPageData(1, ucPageNav.OnePageCount, out int total);
                ucPageNav.InitiControl(total);
            }
            else
            {
                GetPageData(0, 0, out _);
            }
        }

        private void GetPageData(int pageNo, int pageSize, out int total)
        {
            if (ucPageNav.Visible)
            {
                QueryArg.PageNo = pageNo;
                QueryArg.PageSize = pageSize;
            }
            SetQueryArg();
            var ret = BLLObj.GetReportData(QueryArg);
            if (!ret)
            {
                tslb01.Text = $"记录数：0";
                total = 0;
                ShowMessage(ret.msg);
                return;
            }

            if (ret.data.DetailData == null || ret.data.DetailData.RowCount == 0)
            {
                dgv.DataSource = null;
                total = 0;
                return;
            }
            total = ret.data.DetailData.RowTotal;
            dgv.DataSource = ret.data.DetailData.ToDataTable();
            tslb01.Visible = statusStrip.Visible;
            if (tslb01.Visible)
            {
                tslb01.Text = $"记录数：{dgv.RowCount}";
            }
            if (ret.data.SumInfoList?.Count > 0)
            {
                statusStrip.Visible = true;
                foreach (var item in ret.data.SumInfoList)
                {
                    statusStrip.Items.Add(new ToolStripStatusLabel($" {item}"));
                }
            }
        }

        void SetQueryArg()
        {
            if (tsTxtSearch.Visible)
            {
                QueryArg.SearchValue = tsTxtSearch.Text;
            }
            SetArg(toolStrip1);
            SetArg(toolStrip2);
            SetArg(toolStrip3);

            void SetArg(ToolStrip toolStrip)
            {
                if (!toolStrip.Visible) return;
                foreach (ToolStripItem item in toolStrip.Items)
                {
                    if (item.Tag == null) continue;
                    var argConfig = item.Tag as Sys_ReportArg;

                    EmControlType cType = (EmControlType)argConfig.ControlType;
                    string val;
                    switch (cType)
                    {
                        case EmControlType.日期时间:
                            val = (item as ToolStripDateTimePicker).Value.ToString(argConfig.DataFormat);
                            break;
                        case EmControlType.时间:
                            val = (item as TollStripTimeSpan).Value.ToString("hh\\:mm");
                            break;
                        case EmControlType.下拉列表:
                            val = (item as ToolStripComboBox).ComboBox.SelectedValue?.ToString();
                            break;
                        case EmControlType.文本框:
                            val = (item as ToolStripTextBox).Text;
                            break;
                        default:
                            continue;
                    }
                    QueryArg.ArgList[argConfig.ArgName] = val;
                }
            }
        }

        private void tsBtnSearch_Click(object sender, EventArgs e)
        {
            if (ReportMain.ReportType == ((int)EmReportType.打印预览))
            {
                RefreshPrintData();
            }
            else
            {
                RefreshData();
            }
        }

        private void tsBtnOut_Click(object sender, EventArgs e)
        {
            if (ExcelNPOI.SaveAsGridView(dgv, ""))
            {
                ShowMessage("导出完成");
            }

        }

        private void tsBtnPrint_Click(object sender, EventArgs e)
        {
            Print(dgv.DataSource);
        }

        private void tsTxtSearch_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                RefreshData();
            }
        }
    }
}